<?php

/**
 * Backhand script for uplading a Model
 * @package ModuleGestionDocuments
 * @version 1.0b
 */

session_start();

// Configuration file
include '../configuration.php';
// Functions
include '../inc/functions.php';

// Include all objects
// TODO: Include only needed classes
foreach (glob($configuration['webroot'].'objects/*.php') as $class) { include_once $class; }

if (!empty($_FILES)) {

	try {
		// Creating Document object in database
		$model = new Model();
		$model->extension = substr(strrchr($_FILES['Filedata']['name'], '.'), 1);
		$model->filename = basename($_FILES['Filedata']['name'], '.'.$model->extension);
		$model->date = date('Y-m-d H:i');
		$model->SetCrmuser(unserialize($_SESSION['current_user']));
		$modelId = $model->SaveNew();

		// Moving file to its location
		$targetPath = $_SERVER['DOCUMENT_ROOT'].$_REQUEST['folder'].'/';
		$targetFile = str_replace('//', '/', $targetPath).$modelId.'.'.$model->extension;
		
		move_uploaded_file($_FILES['Filedata']['tmp_name'], $targetFile);
		echo str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetFile);
		
	} catch (Exception $e) {
		error_log($e->getMessage());
	}
}
?>